package com.senac.lucas.seguranca;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;

import com.senac.lucas.domain.Role;
import com.senac.lucas.domain.Usuario;

@Name("autenticador")
public class Autenticador {
   
   @In 
   private EntityManager entityManager;
   
   @In 
   private Credentials credentials;
   
   @In 
   private Identity identity;

   public boolean login() {
      try {
    	  Usuario user = (Usuario) entityManager.createQuery(
            "from Usuario where usuario = :usuario and senha = :senha")
            .setParameter("usuario", credentials.getUsername())
            .setParameter("senha", credentials.getPassword())
            .getSingleResult();

         if (user.getRoles() != null) {
            for (Role mr : user.getRoles())
               identity.addRole(mr.getNome());
         }

         return true;
      }
      catch (NoResultException ex) {
         return false;
      }

   }

}
